import { Component, OnInit, Input, OnDestroy, AfterViewInit, ViewChildren, ViewChild } from '@angular/core';
import { TreeNode, ConfirmationService, DialogService } from 'primeng/api';
import { TabComponent } from '../tab-details';
import { HttpClient } from '@angular/common/http';
import { TabFormPrintComponent } from './tab-form-print.component';
import { FbDynamicFormComponent } from '../../../../form/design/drawer/fb-dynamic-form.component';

@Component({
    templateUrl: './tab-form.component.html',
    styleUrls: ['./tab-form.component.scss']
})
export class TabFormComponent implements OnInit, OnDestroy, TabComponent {
    @Input() data: any;

    @ViewChild(FbDynamicFormComponent, { static: false })
    private fbDynamicFormComponent: FbDynamicFormComponent;
    loading = true;
    actInst: any = {};
    /**  文书列表 */
    forms: TreeNode[] = [];

    formId: number = 0;
    selectedForm: any;

    recId: number = 0;
    actId: number = 0;
    actDefId: number = 0;
    bizId:number = 0;

    constructor(
        private http: HttpClient,
        private dialogService: DialogService,
        private confirmationService: ConfirmationService
    ) { }

    /** 加载案件相关文书 */
    ngOnInit() {
        this.recId = this.data.recId;
        this.actId = this.data.actId;
        this.actDefId = this.data.actDefId;
        this.bizId = this.data.bizId;
        this.http.get('/' + this.data.systemUrl + '/api/tab/form/listformtree?recId=' + this.recId + '&actDefId=' + this.actDefId + '&bizId=' + this.bizId).subscribe(data => {
            this.forms = data['data'];
            this.loading = false;
            if (this.forms.length > 0) {
                let temp = this.forms[0];
                while (temp.icon.indexOf('folder') >= 0) {
                    temp = temp.children[0];
                }
                this.selectedForm = temp;
                this.nodeSelect(null);
            }
        });
    }

    /** 文书选择 */
    nodeSelect($event) {
        this.formId = this.selectedForm['id'];
        this.fbDynamicFormComponent.onLoadValue(this.data.recId, 0, this.formId, this.actDefId, this.bizId);
    }

    /** 文书保存 */
    saveForm() {
        this.fbDynamicFormComponent.onSubmit(this.data.recId, 0, this.formId, this.bizId);
    }

    ngOnDestroy() {
        /** 离开时提示保存，暂未实现，无类似 onBeforeDestory 相关方法 */
        if (this.fbDynamicFormComponent.isDitry()) {
        }
    }

    /** 显示文书打印功能 */
    printForm() {
        const dialog = this.dialogService.open(TabFormPrintComponent, {
            header: '文书打印预览',
            width: '100%',
            data: {
                'rowData': this.data,
                'systemUrl': this.data.systemUrl
            },
            contentStyle: { 'height': $('body').height() - 50 + 'px', 'padding': '0' }
        });
    }
}
